package com.shisfish.library.Utils.FileUpload;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * 文件上传组件（包含表单值）
 * @author Administrator
 * @return JsonArray
 */
public class FileUploadUtils {

	//类加载时加载
	public static String filePath="";
	
	public FileUploadUtils() {
		// TODO Auto-generated constructor stub
	}
	
	@SuppressWarnings("unchecked")
	public JSONArray getRiverWayUpload(@Context HttpServletRequest request) {

		// 下面的注释代码不要删。
		/*
		 * response.setCharacterEncoding("UTF-8"); String msg = "上传失败！"; Boolean
		 * flag=false; Map<String, String> map= new HashMap<String, String>();
		 * String objectNameStr = ""; String docbelongStr=""; String
		 * fileName1=""; String fileFormat=""; String saveFilePath=""; boolean
		 * isMultipart = ServletFileUpload.isMultipartContent(request);
		 * 
		 * if (isMultipart) { // 构造一个文件上传处理对象 FileItemFactory factory = new
		 * DiskFileItemFactory(); ServletFileUpload upload = new
		 * ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); //
		 * 支持中文文件名 List list = new ArrayList<FileItem>();
		 * 
		 * // 解析表单中提交的所有文件内容 try { list = upload.parseRequest(request); } catch
		 * (FileUploadException e1) { // TODO Auto-generated catch block
		 * e1.printStackTrace(); } for (int i = 0; i < list.size(); i++) {
		 * FileItem item = (FileItem) list.get(i); if(item.isFormField()){
		 * //普通表单值 try { map.put(item.getFieldName(), item.getString("UTF-8"));
		 * } catch (UnsupportedEncodingException e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); } }else { String name =
		 * item.getName(); //获得上传的文件名（IE上是文件全路径，火狐等浏览器仅文件名） fileName1 =
		 * name.substring( name.lastIndexOf(‘\\’) + 1, name.length());
		 * fileFormat=fileName1.substring(fileName1.lastIndexOf(".")); //文件扩展名
		 * objectNameStr = map.get("objectName"); //实体id docbelongStr =
		 * map.get("docbelong"); //文件归属
		 * 
		 * //上传文件的保存的位置 // saveFilePath
		 * =PropertiesReader.getValue("agcom.fileupload.Path"
		 * )+File.separator+objectNameStr; //
		 * saveFilePath=pathHandle(objectNameStr, docbelongStr);
		 * 
		 * // saveFilePath = request.getRealPath("/fileupload"); // absolutePath
		 * = projectLayerId+"/"+fileName; // parseFile(item, filePath); //上传操作
		 * // flag=upload4Stream(fileName, saveFilePath, item.getInputStream());
		 * //上传文件 if(flag){ msg = "上传成功！"; } } }}
		 */
		String json = "";
		String fileName = null;
		String newFileName = null;
		String newName = null;
		String extName = null;
		String file_size = null;
		JSONArray jsArr = null;
		File file = new File(filePath);   // 上传文件保存位置
		// 如果该目录不存在，则创建目录
		if (!file.exists()) {
			file.mkdir();
		}
		
		try {
			// 判断是否上传文件表单,也就是form中是否有enctype="multipart/form-data"项;必须post提交,get提交对内容长度有限制
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory diskfileFactory = new DiskFileItemFactory();
				diskfileFactory.setSizeThreshold(1024 * 215);// 设置缓冲区大小
				ServletFileUpload fileUpload = new ServletFileUpload(
						diskfileFactory);
				fileUpload.setHeaderEncoding("utf-8");
				// fileUpload.setSizeMax(1000 * 1024 * 1024);
				fileUpload.setFileSizeMax(1000 * 1024 * 1024);
				List<Map<String,String>> MapList = new ArrayList<Map<String,String>>();
				List<FileItem> fileItems = fileUpload
						.parseRequest((HttpServletRequest) request);// 获取所有表单
				for (FileItem item : fileItems) {
					Map<String, String> hashMap = new HashMap<String, String>();
					if (item.isFormField()) { // 普通表单值
						hashMap.put("form_type","form");
						hashMap.put(item.getFieldName(),
								item.getString("UTF-8"));
						//System.out.println(item);
						MapList.add(hashMap);
					}
					if (!item.isFormField()) { 		// 是文件
						fileName = item.getName();
						//System.out.println("上传的文件名为：" + fileName);
						//System.out.println("上传的文件大小为：" + item.getSize());
						file_size = String.valueOf(item.getSize());
						if (item.getSize()>0) {
							hashMap.put("form_type","file");
							extName = fileName.substring(fileName
									.lastIndexOf("."));
							newName = fileName.substring(0,
									fileName.lastIndexOf("."));
							newFileName = filePath + newName + extName;
							//System.out.println("文件扩展名为：" + extName);
							//System.out.println("新文件名：" + newFileName);
							// newFileName = getTomcatRealPath(newFileName);
							
							File uploadFile = new File(newFileName);
							if (uploadFile.exists()) {
								uploadFile.delete();
							}
							
							item.write(new File(newFileName));
							
							hashMap.put("file_type", extName);
							hashMap.put(item.getFieldName(), fileName);
							hashMap.put("file_path", newFileName);
							// 保留两位小数
							DecimalFormat fnum = new DecimalFormat("##0.00");
							// 大小单位是（kb） 也可以是mb 再除1024
							file_size = fnum.format(Float.parseFloat(file_size) / 1024);
							hashMap.put("file_size", file_size);
							MapList.add(hashMap);
							json = "1";
						}
					}
				}
				
				jsArr = JSONArray.fromObject(MapList);
				//System.out.println("组件返回值："+jsArr.toString());
				/*// 时间控制 使用数据库中的getdate
				// spring security 获取session中 当前登陆的用户名
				UserDetails userDetails = (UserDetails) SecurityContextHolder
						.getContext().getAuthentication().getPrincipal();
				String username = userDetails.getUsername();
				System.out.println(username);
				hashMap.put("UPDATE_USER", username);*/
				// 上传的文件，将文件的路径保存到数据库
				// int count = riverWayService.modifyProgress(hashMap);
			} else {
				json = "2";
				throw new RuntimeException("请设置form表单的enctype属性");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json = "0";
		}
		System.out.println(json);
		return jsArr;
	}
	
	
	public String getFilePath() {
		return filePath;
	}


	@SuppressWarnings("static-access")
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	
}
